package com.zpark.h5.controller;

import com.zpark.h5.service.IAlipayH5Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 手机网站支付控制层
 */
@RestController
@RequestMapping("/h5")
public class AlipayH5Controller {

    @Autowired
    private IAlipayH5Service alipayH5Service;

    /**
     * 创建订单
     * @return
     */
    @RequestMapping("/createOrder")
    public void createOrder(HttpServletResponse response) {
        // 调用业务层方法，获取请求支付页面的form表单字符串
        String form = alipayH5Service.createOrder();

        // 将结果展示到浏览器
        try {
            // 设置响应编码
            response.setContentType("text/html;charset=utf-8");

            PrintWriter writer = response.getWriter();
            writer.write(form);
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 退款
     * @param orderId 订单id
     */
    @RequestMapping("/refund")
    public String refund(String orderId) {
        // 调用业务层方法
        alipayH5Service.refund(orderId);

        return "Success 退款成功";
    }


    /**
     * 用户支付成功异步回调url
     * @param request 请求对象
     */
    @RequestMapping("/notify")
    public void notify(HttpServletRequest request) {
        // 调用业务层方法
        alipayH5Service.payNotify(request);
    }

    /**
     * 请求成功同步回调地址
     * @param response 响应对象
     */
    @RequestMapping("/success")
    public void success(HttpServletResponse response) {
        // 将结果展示到浏览器
        try {
            // 设置响应编码
            response.setContentType("text/html;charset=utf-8");

            PrintWriter writer = response.getWriter();
            writer.write("<center><h1 style='color: red'>用户支付成功，将来替换为自己的支付成功页面</h1></center>");
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 请用户取消支付回调地址
     * @param response 响应对象
     */
    @RequestMapping("/quit_pay")
    public void quitPay(HttpServletResponse response) {
        // 将结果展示到浏览器
        try {
            // 设置响应编码
            response.setContentType("text/html;charset=utf-8");

            PrintWriter writer = response.getWriter();
            writer.write("<center><h1 style='color: red'>用户取消支付</h1></center>");
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
